package br.com.farmabid.controller;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.inject.Inject;

import br.com.caelum.vraptor.Result;
import br.com.farmabid.component.AcessSession;

public abstract class BasicController implements IController {
	@Inject protected Result result;
	@Inject protected AcessSession session;
	@Inject protected ResourceBundle bundle;
	private List<String> errors = new ArrayList<String>();

	protected abstract void redirect();

	protected Boolean resultPossui(String nomeItem){
		Map<String, Object> res = result.included();
		if(!res.containsKey(nomeItem)){
			return false;
		}
		return true;
	}
	
	protected Boolean resultPossuiConteudo(String nomeItem){
		Map<String, Object> res = result.included();
		if(res.containsKey(nomeItem)){
			try {
				List<String> lista = (List<String>) res.get(nomeItem);
				if(lista != null && lista.size() > 0){
					return true;
				}
			} catch (ClassCastException e) {
				return true;
			}
			
		}
		return false;
	}

	public AcessSession getSession() {
		return session;
	}

	public void setSession(AcessSession session) {
		this.session = session;
	}
	
	public void injetaUsuario(){
		result.include("acessSession", session);
	}
	
	protected void mensagemSucesso(String resource){
		result.include(SUCESS, recuperaMensagem(resource));
	}

	protected void mensagemErro(String resource){
		result.include(ERROR, recuperaMensagemErro(resource));
	}
	
	protected void mensagemErro(String resource, Object... parameters){
		result.include(ERROR, recuperaMensagemErro(resource, parameters));
	}

	protected void mensagem(String resource){
		result.include(MESSAGE, recuperaMensagem(resource));
	}

	protected String recuperaMensagem(String resource){
		return bundle.getString(resource);
	}
	
	protected List<String> recuperaMensagemErro(String resource, Object... parameters){
		MessageFormat   messageFormat = new MessageFormat(bundle.getString(resource));
		Object[] args = parameters;
		errors.add(messageFormat.format(args));
		return errors;
	}
	
	protected List<String> recuperaMensagemErro(String resource){
		errors.add(bundle.getString(resource));
		return errors;
	}

}